package com.quanquan.user.service.autoCompute.service;

import DTO.PageDTO;
import com.alibaba.fastjson.JSONArray;
import com.quanquan.user.service.autoCompute.entity.LabelGroupSynRecord;
import com.quanquan.user.service.autoCompute.repository.LabelGroupSynRecordRepository;
import com.quanquan.user.service.autoCompute.request.LabelGroupRequestBody;
import exceptions.service.ServiceRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import utils.CsvUtil;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName SynRecordService
 * @Description
 * @Author Owen
 * @Date 2020/3/13 0013 下午 4:55
 * @Version V1.0
 **/
@Slf4j
@Service
public class SynRecordService {

    @Autowired
    private LabelGroupSynRecordRepository labelGroupSynRecordRepository;

    /**
     * 分页获取结果
     *
     * @param requestBody
     * @return
     */
    public PageDTO<LabelGroupSynRecord> list(LabelGroupRequestBody requestBody, String groupId) throws ServiceRuntimeException {

        if (requestBody.getPage() == null || requestBody.getPage() < 1) {
            throw new ServiceRuntimeException("分页参数不合法");
        }

        if (requestBody.getSize() == null || requestBody.getSize() < 1) {
            throw new ServiceRuntimeException("分页参数不合法");
        }

        Integer currPage = requestBody.getPage() - 1;

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");

        Pageable pageable = PageRequest.of(currPage, requestBody.getSize(), sort);

        Page<LabelGroupSynRecord> page = labelGroupSynRecordRepository.findAll((Specification<LabelGroupSynRecord>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("groupId").as(String.class), groupId));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);

        PageDTO<LabelGroupSynRecord> pageResult = new PageDTO<>();

        pageResult.setPageSize(requestBody.getSize());

        pageResult.setPage(requestBody.getPage());

        pageResult.setKeyword(requestBody.getKeyword());

        pageResult.setTotal(page.getTotalElements());

        List<LabelGroupSynRecord> content = page.getContent();

        pageResult.setList(content);

        return pageResult;

    }

    public byte[] exportData(HttpServletResponse response, List<Object> records) throws Exception {

        String[] titles = {"手机号","姓名","卡号","性别","生日","注册时间"};

        List<List<Object>> rows = new LinkedList<>();
        records.forEach(dto -> {
            List<String> strings = JSONArray.parseArray(dto.toString(), String.class);
            List<Object> row = new LinkedList<>();
            row.add(strings.get(1));
            row.add(strings.get(2));
            row.add(strings.get(3));
            if(strings.get(4).equals(0)){
                row.add("男");
            }else if(strings.get(4).equals(1)){
                row.add("女");
            }else{
                row.add("保密");
            }
            row.add(strings.get(4));
            row.add(strings.get(5));
            row.add(strings.get(6));
            rows.add(row);
        });
        ByteArrayOutputStream os = CsvUtil.doExport(titles, 6, rows);
        byte[] content = os.toByteArray();
        return content;
    }


}
